<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="90px" :rules="formRules">
      <el-form-item label="原始密码" prop="oldPwd">
        <el-input v-model="form.oldPwd" type="password" placeholder="请输入原始密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="form.newPwd" type="password" placeholder="请输入6-18位新密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPwd">
        <el-input v-model="form.confirmPwd" type="password" placeholder="请再次输入新密码" />
      </el-form-item>
      <br>
      <el-form-item class="footer">
        <el-button type="primary" @click="onSubmit">确认修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import profileApi from '@/api/profile'
export default {
  name: 'Profile',
  data() {
    return {
      form: {},
      formRules: {
        oldPwd: [{ required: true, trigger: 'blur', message: '请输入原始密码' }],
        newPwd: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value === '' || (value.length < 6 || value.length > 18)) {
                callback(new Error('请输入6-18位新密码'))
              } else {
                callback()
              }
            }
          }
        ],
        confirmPwd: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请再次输入密码'))
              } else if (value !== this.form.newPwd) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          profileApi.changePwd(this.form).then(res => {
            this.$message({
              showClose: true,
              message: '修改成功，即将退出登录',
              type: 'success'
            })
            setTimeout(() => { this.logout() }, 2000)
          }).catch(err => {
            this.$message({
              showClose: true,
              message: '修改失败，请重试',
              type: 'error'
            })
          })
        } else {
          console.log('validate failure!!')
          return false
        }
      })
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=/`)
    }
  }
}
</script>

<style lang="scss" scoped>
  .app-container {
    display: flex;
    justify-content: center;
  }
  .el-form {
    width: 350px;
    margin-top: 50px;
    .footer {
      .el-button {
        width: 100%;
      }
    }
  }
</style>
